package com.wanshu.sys.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wanshu.common.constant.SystemConstant;
import com.wanshu.common.result.JWTUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TokenVerifyFilter extends BasicAuthenticationFilter {

    public TokenVerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public TokenVerifyFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }

    //校验提交的token是否合法
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        if(header != null && header.startsWith(SystemConstant.SYS_TOKEN_PREFIX)){
            //获取正常的token消息
            String token = header.replace(SystemConstant.SYS_TOKEN_PREFIX, "");
            //校验token是否合法
            DecodedJWT verify = JWTUtils.verify(token);
            if(verify == null){
                //校验失败, 给用户提示
                responseLogin(response);
            }
            String username = verify.getClaim("username").asString();
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
            //根据帐号获取相关权限
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, "", grantedAuthorities);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放过请求
            chain.doFilter(request, response);
        }else {
            responseLogin(response);
        }
    }

    private void responseLogin(HttpServletResponse response) throws IOException{
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = response.getWriter();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
        resultMap.put("msg", "请先登录");
        writer.write(JSON.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

}
